# !/usr/bin/env python3
# -*- coding: utf-8 -*-


import xmltodict
import json
import os
from os import listdir


# '''json to xml'''
def json_to_xml(json_str):
    # xmltodict库的unparse()json转xml
    # 参数pretty 是格式化xml
    json_str = json.loads(json_str)
    xml_str = xmltodict.unparse(json_str, pretty=1)
    return xml_str


# '''json to xml without root'''
def json_to_xml_without_root(json_str, root1, root2):
    # xmltodict库的unparse()json转xml
    # 参数pretty 是格式化xml
    json_str = json.loads(json_str)
    json_str = {root2: json_str}
    json_str = {root1: json_str}
    xml_str = xmltodict.unparse(json_str, pretty=1)
    return xml_str


# '''xml to json'''
def xml_to_json(xml_str):
    # parse是的xml解析器
    xml_parse = xmltodict.parse(xml_str)
    # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
    # dumps()方法的ident=1,格式化json
    json_str = json.dumps(xml_parse, indent=1, sort_keys=False)
    return json_str


def xml_file_to_json_file(xml_file):
    with open(xml_file, 'r', encoding='UTF-8') as f1:
        xmlfile = f1.read()
        print('---------xml文件-----------')
        print(xmlfile)
        print('---------json文件----------')
        print(xml_to_json(xmlfile))
    with open(xml_file[:-3] + 'json', 'w', encoding='UTF-8') as newfile:
        newfile.write(xml_to_json(xmlfile))
        print('--------写入json文件--------')
        print('写入json文件成功')


def json_file_to_xml_file(json_file):
    with open(json_file, 'r', encoding='UTF-8') as f1:
        jsonfile = f1.read()
        print('---------json文件-----------')
        print(jsonfile)
        print('---------xml文件----------')
        print(json_to_xml(jsonfile))
    with open(json_file[:-4] + 'xml', 'w', encoding='UTF-8') as newfile:
        newfile.write(json_to_xml(jsonfile))
        print('--------写入xml文件--------')
        print('写入xml文件成功')


def json_file_to_xml_file_without_root(json_file, root1, root2):
    with open(json_file, 'r', encoding='UTF-8') as f1:
        jsonfile = f1.read()
        print('---------json文件-----------')
        print(jsonfile)
        print('---------xml文件----------')
        print(json_to_xml_without_root(jsonfile, root1, root2))
    with open(json_file[:-4] + 'xml', 'w', encoding='UTF-8') as newfile:
        newfile.write(json_to_xml_without_root(jsonfile, root1, root2))
        print('--------写入xml文件--------')
        print('写入xml文件成功')


def remove_xml_files(remove_path):
    for file_name in listdir(remove_path):
        if file_name.endswith('.xml'):
            os.remove(remove_path + file_name)

